/*
 * @Author: zhaoxiangyu@
 * @Date: 2021-12-05 12:30:19
 * @LastEditors: 647355931@qq.com
 * @LastEditTime: 2021-12-17 18:03:51
 * @Description: file content
 */
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import Radio from './index';
import './RadioGroup.css';

function RadioGroup(props) {
  const { options, defaultValue, layout, button,radioItemChange } = props;
  const [selectValue, setSelectValue] = useState(defaultValue || null);
  // console.log('selectValue ===> ', selectValue)
  // console.log('RadioGroup 一次 ====> ')

  return (
    <div className={`${layout === 'vertical' ? 'RadioVertical' : 'RadioHorizontal'}`}>
      {options.map((item, index) => (
        <Radio
          key={index}
          checked={selectValue && selectValue === item.value ? true : item.checked}
          disabled={item.disabled}
          onChange={(v, l) => {setSelectValue(v); radioItemChange(v)}}
          button={button}
          {...item}
        >
          {item.label}
        </Radio>
      ))}
    </div>
  );
}

// 入参类型检查
RadioGroup.prototype = {
  // 可选项数组，例：[{label: '选项一', value: 1}, {label: '选项2', value: 2, disabled: true}]
  options: PropTypes.arrayOf((propValue, key, componentName, location, propFullName) => {
    if (typeof propValue[key] !== 'object') {
      return new Error(
        `Invalid prop \`${propFullName}\` of type \`${typeof propValue[
          key
        ]}\` supplied to \`${componentName}\`, expected \`object\``
      );
    }
    if (!propValue[key].hasOwnProperty('label')) {
      return new Error(
        `\`${componentName}\`组件的 prop 参数\`${propFullName}\`缺少属性\`label\``
      );
    }

    if (!propValue[key].hasOwnProperty('value')) {
      return new Error(
        `\`${componentName}\`组件的 prop 参数\`${propFullName}\`缺少属性\`value\``
      );
    }
  }).isRequired,
  layout: PropTypes.oneOf(['horizontal', 'vertical']),
  value: PropTypes.any,
  disabled: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  // 是否显示按钮样式
  button: PropTypes.bool,
  className: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.array,
    PropTypes.objectOf(PropTypes.bool),
  ]),
  radioItemChange: PropTypes.func
};

RadioGroup.defaultProps = {
  layout: 'horizontal'
};

export default RadioGroup;
